var arrayUtils = require("arrayUtils")
var objectUtils = require("objectUtils")

var $ = exports

var tagProto = {isTag: true}
var newTag = function(name, attrs, elems) {
	var t = objectUtils.beget(tagProto)
	if (name) { t.name = name }
	if (attrs) { t.attrs = attrs }
	if (elems.length != 0) { t.elems = elems }
	return t
}

var isAttrs = function(o) {
	return o && (!!!o.isTag) && o.constructor === Object
}

var canonizeAttrs = function(attrs) {
	for (var key in attrs) {
		attrs[key] = "" + attrs[key] 
	}
	return attrs
}

var tag = function() {
	var name = arguments[0]
	var attrs = isAttrs(arguments[1]) ? canonizeAttrs(arguments[1]) : null
	var elems = arrayUtils.fromArguments(arguments, attrs ? 2 : 1).flatten().map(function(e) {
		return (!!e.isTag) ? e : "" + e
	})
	return newTag(name, attrs, elems)
}

require("rosa/html4Tags").all.forEach( function(t) {
	$[t] = function() {
		var args = [t]
		for( var i=0; i<arguments.length; i++) {
			args.push(arguments[i])
		}
		return tag.apply({}, args)
	}
})

$.fetchMods = function(path) {
	var libs = arrayUtils.fromArguments(arguments, 1)
	return $.script(
		{
			src: path + "?modules=" + libs.join(","), 
			"type":"text/javascript"
		}, 
		" "
	)
}